/**
 * Created by dean on 2017/10/15.
 */
import React, {Component} from "react";
import axios from "axios";
import {
    Panel,
    Glyphicon,
    PageHeader
} from "react-bootstrap";
const markdownListUrl = "http://www.zhangfuwen.com/markdown/book/SUMMARY.md?json=true";


class MarkdownArticle extends Component {
    constructor(props) {
        super(props)
        this.state = {
            content: []
        }
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.markdownPath !== nextProps.markdownPath) {
            var url = "http://www.zhangfuwen.com/markdown/book/" + nextProps.markdownPath + "?json=true"
            axios.get(url)
                .then(res => {
                    const posts = res.data;
                    this.setState({content: posts});
                });
        }
    }

    componentDidMount() {
        var url = "http://www.zhangfuwen.com/markdown/book/" + this.props.markdownPath + "?json=true"
        axios.get(url)
            .then(res => {
                const posts = res.data;
                this.setState({content: posts});
            });
    }

    componentDidUpdate(){
        window.scrollTo(0,0)
    }

    render() {
        if (this.state.content === null || this.state.content === undefined) {
            return <li></li>
        }
        return (
            <div>
                <h1>{this.state.content.Title}</h1>
                <hr/>
                <div dangerouslySetInnerHTML={{__html: this.state.content.Content}}></div>
            </div>

        )
    }
}
class MarkdownListPanel extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentSelected: 0,
            markdownList: [],
        };
    }
    showMarkdown(filename,index) {
        this.setState({ currentSelected :index})
        this.props.onMarkdownSelected(filename)
    }

    componentDidMount() {
        axios.get(markdownListUrl)
            .then(res => {
                const posts = res.data;
                this.setState({markdownList: posts});
            });
    }

    render() {
        return (
            <Panel>
                <PageHeader>Markdown
                    <small>gitbooks</small>
                </PageHeader>
                <div> {this.state.markdownList.map(function (elem, i) {
                    return (
                        <li key={i}>
                            <a onClick={this.showMarkdown.bind(this, elem.FileName, i)}>
                                <Glyphicon glyph="pencil"/> {elem.Title}
                            </a>
                        </li>
                    )
                }, this)
                }</div>
            </Panel>
        )
    }
}

export { MarkdownArticle, MarkdownListPanel }
